<template>
	<view class="invite-friends">
		<block v-if="show">
			<view class="banner">
				<lw-swiper class="z-index" :list="swiperList" :effect3d="true" :autoplay="false" :circular="false" mode="number"
				 height="1080" bg-color="#fff" border-radius="10" name="url" effect3d-previous-margin="68" @change="swiperChange"></lw-swiper>
			</view>
			<view class="btn-group">
				<view class="preserve" @click="poster">
					生成海报
				</view>
			</view>
			<!-- 海报 -->
			<uni-popup type="center" ref="poster">
				<view class="poster">
					<canvas id="poster" class="poster-canvas" canvas-id="poster" style="width: 614rpx; height: 980rpx;"></canvas>
					<view class="save" @click="savePoster">保存到相册</view>
				</view>
			</uni-popup>
			<!-- 打开小程序设置 -->
			<pt-openSetting ref="openSetting" :tips="tips"></pt-openSetting>
			<pt-nothing text="暂无海报" :fixed="true" v-if="swiperList.length == 0" icon="https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/images/shop/icons/nothing.png?v=1">
			</pt-nothing>
		</block>

		<pt-loading></pt-loading>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				show: false,
				tips: '您已关闭相册访问开关，请打开开关后重新保存',
				swiperList: [],
				index: 0,
				// canvas
				userName: '',
				phone: '',
				mainPic: 'http://jiajudashi.oss-cn-shenzhen.aliyuncs.com/images/major_img/middle_img/154820981115437.jpeg',
				phoneIcon: 'https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/static/images/other/2020-08-27/20200827/efa5b769d6837b099ea3c8fb43d59851.png',
				QRcode: 'https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/static/images/qrcode_goods/2020-08-07/15967966173051.png'
			};
		},
		onLoad() {
			this.init()
		},
		methods: {
			init() {
				let data = {
					limit: 100,
					store_id: uni.getStorageSync('userInfo') ? JSON.parse(uni.getStorageSync('userInfo')).store_id : 1
				}
				this.$u.apiWei.PosterLists(data).then(res => {
					this.swiperList = res.datas
					this.show = true
				})
			},
			swiperChange(index) {
				this.index = index
			},
			// canvas
			poster() {
				this.userName = this.swiperList[this.index].user.nickname
				this.mainPic = this.swiperList[this.index].image
				this.QRcode = this.swiperList[this.index].user.qrcode
				this.phone = this.swiperList[this.index].user.phone
				this.$refs.poster.open()
				this.$nextTick(() => {
					this.OnCanvas()
				})
			},
			async OnCanvas() {
				let _this = this;
				_this.ctx = uni.createCanvasContext('poster', this);
				const systemInfo = uni.getSystemInfoSync()
				const proImgInfo = await _this.getImageInfo({
					imgSrc: _this.mainPic
				}); // 主图
				const phoneIconImgInfo = await _this.getImageInfo({
					imgSrc: _this.phoneIcon
				}); // 电话图标
				const QRcodeImgInfo = await _this.getImageInfo({
					imgSrc: _this.QRcode
				}); // 二维码
				_this.canvasW = uni.upx2px(614);
				_this.canvasH = uni.upx2px(980);

				_this.ctx.setFillStyle('#FFFFFF');
				_this.ctx.fillRect(0, 0, _this.canvasW, _this.canvasH)

				// 绘制产品图
				_this.ctx.drawImage(proImgInfo.path, 0, 0, uni.upx2px(614), uni.upx2px(638));

				//绘制用户电话
				const phone = this.phone
				_this.ctx.setFontSize(uni.upx2px(28));
				_this.ctx.setFillStyle('#444444');
				_this.ctx.fillText(phone, uni.upx2px(80), uni.upx2px(822));

				// 绘制电话图标
				_this.ctx.drawImage(phoneIconImgInfo.path, uni.upx2px(30), uni.upx2px(794), uni.upx2px(32), uni.upx2px(32))
				_this.ctx.restore()

				//用户名
				const userName = this.userName
				_this.ctx.setFillStyle('#141414');
				_this.ctx.font = 'normal bold 16px Microsoft YaHei';
				if (userName.length > 20) {
					_this.ctx.fillText(userName.substring(0, 20) + '...', uni.upx2px(30), uni.upx2px(750));
				} else {
					_this.ctx.fillText(userName, uni.upx2px(30), uni.upx2px(750));
				}

				// 绘制二维码
				_this.ctx.drawImage(QRcodeImgInfo.path, uni.upx2px(400), uni.upx2px(690), uni.upx2px(170), uni.upx2px(170));

				// 绘制二维码提示上面的灰色线
				_this.ctx.moveTo(0, uni.upx2px(920));
				_this.ctx.lineTo(uni.upx2px(614), uni.upx2px(920));
				_this.ctx.lineWidth = 1;
				_this.ctx.strokeStyle = "#F5F5F5";
				_this.ctx.stroke();

				// 绘制二维码提示
				const tips = '微信扫码进入小程序'
				_this.ctx.setFillStyle('#6B6B6B');
				_this.ctx.font = 'normal nomal 10px Microsoft YaHei';
				let width = _this.ctx.measureText(tips).width
				if(width == 0)width = 78
				_this.ctx.fillText(tips, uni.upx2px(307 - width), uni.upx2px(960));


				//延迟后渲染至canvas上
				setTimeout(function() {
					_this.ctx.draw();
				}, 600);
			},

			async getImageInfo({
				imgSrc
			}) {
				uni.showLoading({
					title: '正在生成海报',
					mask: true
				})
				return new Promise((resolve, errs) => {
					if (imgSrc.indexOf('https') != -1) {
						uni.downloadFile({
							url: imgSrc,
							success: function(res) {
								uni.getImageInfo({
									src: res.tempFilePath,
									success: function(image) {
										uni.hideLoading()
										resolve(image);
									},
									fail(err) {
										uni.hideLoading()
										uni.showToast({
											title: '生成失败，请退出重试',
											icon: 'none',
											duration: 1500
										})
										errs(err);
									}
								});
							}
						})
					} else {
						uni.getImageInfo({
							src: imgSrc,
							success: function(image) {
								uni.hideLoading()
								resolve(image);
							},
							fail(err) {
								uni.hideLoading()
								uni.showToast({
									title: '生成失败，请退出重试',
									icon: 'none',
									duration: 1500
								})
								errs(err);
							}
						});
					}
				});
			},
			savePoster() {
				uni.showLoading({
					title: '正在保存',
					mask: true
				})
				uni.canvasToTempFilePath({
					destWidth: 614,
					destHeight: 980,
					canvasId: 'poster',
					success: (data) => {
						uni.hideLoading()
						// #ifdef APP-PLUS || H5
						uni.saveImageToPhotosAlbum({
							filePath: data.tempFilePath,
							success: (saveRes) => {
								uni.showToast({
									icon: 'none',
									title: '保存成功，请在相册中查看',
									duration: 1500
								})
							},
							fail: (fail) => {
								uni.showToast({
									icon: 'none',
									title: '保存失败',
									duration: 1500
								})
							}
						})
						// #endif
						// #ifdef MP-WEIXIN
						uni.getSetting({
							withSubscriptions: true,
							success: (scope) => {
								if(!scope.authSetting['scope.writePhotosAlbum']){
									uni.authorize({
										scope: 'scope.writePhotosAlbum',
										success: () => {
											uni.saveImageToPhotosAlbum({
												filePath: data.tempFilePath,
												success: (saveRes) => {
													uni.showToast({
														icon: 'none',
														title: '保存成功，请在相册中查看',
														duration: 1500
													})
												},
												fail: (fail) => {
													uni.showToast({
														icon: 'none',
														title: '保存失败',
														duration: 1500
													})
												}
											})
										},
										fail: () => {
											// uni.showToast({
											// 	icon: 'none',
											// 	title: '您已关闭相册访问开关，请开启后重新保存'
											// })
											this.$refs.openSetting.init()
										}
									})
								}else{
									uni.saveImageToPhotosAlbum({
										filePath: data.tempFilePath,
										success: (saveRes) => {
											uni.showToast({
												icon: 'none',
												title: '保存成功，请在相册中查看',
												duration: 1500
											})
										},
										fail: (fail) => {
											uni.showToast({
												icon: 'none',
												title: '保存失败',
												duration: 1500
											})
										}
									})
								}
							}
						})
						// #endif
					}
				}, this)
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}

	.invite-friends {
		.banner {
			padding-top: 20rpx;
		}
	}

	.btn-group {
		position: fixed;
		left: calc(50% - 150rpx);
		bottom: 20rpx;
		display: flex;
		justify-content: center;

		.preserve {
			width: 300rpx;
			height: 80rpx;
			line-height: 80rpx;
			font-size: 32rpx;
			text-align: center;
			background: rgba(20, 20, 20, 1);
			border-radius: 8rpx;
			color: #fff;
		}
	}

	.save {
		margin: 40rpx;
		height: 88rpx;
		line-height: 88rpx;
		background: rgba(20, 20, 20, 1);
		border-radius: 8rpx;
		text-align: center;
		color: #FFF;
		font-size: 32rpx;
		font-weight: bold;
	}
</style>
